package cn.zorbus.laian.domain.service;

import lombok.SneakyThrows;
import org.bytedeco.ffmpeg.global.avutil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

@Component
public class VideoCapture implements IVideoCaptureService {

    @SneakyThrows
    public String screenshot(String videoFilePath) {
        avutil.av_log_set_level(avutil.AV_LOG_ERROR);
        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoFilePath)) {
            String screenshotFilePath = videoFilePath + "-SCREENSHOT" + ".png";
            try {
                grabber.start();
                // 读取第一帧
                Frame frame = grabber.grab();
                // 将第一帧保存为图像文件
                if (frame != null) {
                    Java2DFrameConverter converter = new Java2DFrameConverter();
                    BufferedImage bufferedImage = converter.convert(frame);
                    // 保存图像
                    ImageIO.write(bufferedImage, "png", new File(screenshotFilePath));
                }
                return screenshotFilePath;
            } finally {
                grabber.stop();
            }
        }

    }

//    private @NotNull String getScreenshotFilePath(String videoFilePath) {
//        File videoFile = new File(videoFilePath);
//        String videoFileName = videoFile.getName();
//        String screenshotFileName = videoFilePath + "-SCREENSHOT";
////        return videoFile.getParent() + File.separator + screenshotFileName;
//        return screenshotFileName;
//    }

//    public static void main(String[] args) {
//        // 加载 FFmpeg 类库
//        avutil.av_log_set_level(avutil.AV_LOG_ERROR);
//
//        String videoFilePath = "/Users/shishaodong/Desktop/2/2-2 建模和设计的整体流程.mp4";
//        String screenshotPath = screenshot(videoFilePath);
//        System.out.println("Screenshot saved at: " + screenshotPath);
//    }
}
